//
//  XDHomeViewController.m
//  XDEducation
//
//  Created by apple on 2017/4/7.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDHomeViewController.h"
#import "XDHomeAttainmentViewController.h"
#import "XDHomeGradeViewController.h"
#import "XDHomeHabitViewController.h"
#import "ADView.h"

@interface XDHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, weak)  UIView *titleView;
@property (nonatomic, strong) NSMutableArray *buttons;
@property (nonatomic, weak) UIButton *selectButton;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIView *underLineView;
@end

static NSString * const ID = @"home";

@implementation XDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [ADView initLaunchAds];

    //初始化导航栏
    [self initNavitationBar];
    
    // 添加底部内容view
    [self setupBottomView];
    
    //添加子控制器
    [self setUpChildViewController];
    
    //设置标题View
    [self setUpTitleView];
    
    // 不需要自动添加额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
}


#pragma mark - 懒加载按钮数组
- (NSMutableArray *)buttons
{
    if (_buttons == nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}


/**
 初始化导航栏
 */
-(void)initNavitationBar{
    //导航栏中间图片
    UIImageView *midImageView = [[UIImageView alloc]init];
    midImageView.frame = CGRectMake(0, 0, 80, 23);
    midImageView.image = [UIImage imageNamed:@"nav_logo_star_default"];
    self.navigationItem.titleView = midImageView;

    //RightButton设置属性
    UIButton *rightItem = [UIButton buttonWithType:UIButtonTypeCustom];
    rightItem.frame = CGRectMake(0, 0, 33, 25);
    [rightItem setImage:[UIImage imageNamed:@"nav_icon_message_default"] forState:UIControlStateNormal];
    rightItem.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightItem addTarget:self action:@selector(rightItemClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItem];
}

- (void)setupBottomView
{
    // 布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = [UIScreen mainScreen].bounds.size;
    
    // 设置滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    // UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) collectionViewLayout:layout];
    
    collectionView.backgroundColor = UIColor(215, 215, 215);
    
    [self.view addSubview:collectionView];
    // 不显示水平指示器
    collectionView.showsHorizontalScrollIndicator = NO;
    // 开启分页
    collectionView.pagingEnabled = YES;
    _collectionView = collectionView;
    // 设置collectionView数据源,展示cell,需要把子控制器view添加cell
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    // 注册cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}


#pragma mark -添加所有子控制器
- (void)setUpChildViewController {
    
    
    //好习惯
    XDHomeHabitViewController *underClassVC = [[XDHomeHabitViewController alloc] init];
    underClassVC.title = @"好习惯";
    [self addChildViewController:underClassVC];
    
    //好成绩
    XDHomeGradeViewController *onClassVC = [[XDHomeGradeViewController alloc] init];
    onClassVC.title =  @"好成绩";
    [self addChildViewController:onClassVC];
    
    
    //好素养
    XDHomeAttainmentViewController *evaluateVC = [[XDHomeAttainmentViewController alloc]init];
    evaluateVC.title = @"好素养";
    [self addChildViewController:evaluateVC];
    
    
}


#pragma mark -添加标题View
- (void)setUpTitleView {
    
    CGFloat titleViewX = 40;
    CGFloat titleViewY = 0;
    CGFloat titleViewW = ScreenW - 80;
    CGFloat titleViewH = 44;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(titleViewX, titleViewY, titleViewW, titleViewH)];
    self.titleView = titleView;
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    
    NSInteger count = self.childViewControllers.count;
    CGFloat titleBtnW = (ScreenW - 80) / count;
    CGFloat titleBtnH = titleView.height;
    CGFloat titleBtnX = 0;
    CGFloat titleBtnY = 0;
    for (int i = 0; i < count; i++) {
        
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.tag = i;
        UIViewController *vc = self.childViewControllers[i];
        [titleBtn setTitle:vc.title forState:UIControlStateNormal];
        [titleBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [titleBtn setTitleColor:ThemeColor forState:UIControlStateSelected];
        titleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        titleBtnX = titleBtnW * i;
        titleBtn.frame = CGRectMake(titleBtnX, titleBtnY, titleBtnW, titleBtnH);
        [titleView addSubview:titleBtn];
        [self.buttons addObject:titleBtn];
        // 监听按钮
        [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //在这设置button初始的选择状态
        if (i == _selectedButtonTag) {
            
            // 添加下划线
            UIView *underLineView = [[UIView alloc] init];
            underLineView.backgroundColor = ThemeColor;
            [titleView addSubview:underLineView];
            _underLineView = underLineView;
            
            // 中心点x
            underLineView.height = 2;
            underLineView.y = titleView.height - underLineView.height;
            // 1.根据控件内容计算尺寸,然后给控件设置尺寸
            [titleBtn.titleLabel sizeToFit];
            underLineView.width = titleBtn.titleLabel.width + 50;
            // 一定要先设置尺寸 在设置中心点
            underLineView.centerX = titleBtn.centerX;
            
            [self titleClick:titleBtn];
        }
        
        
    }
}


-(void)setSelectedButtonTag:(NSInteger)selectedButtonTag{
    
    _selectedButtonTag = selectedButtonTag;
    //NSLog(@"%ld",(long)_selectedButtonTag);
}

#pragma mark - 选中按钮
- (void)selButton:(UIButton *)button
{
    //重复点击同一个按钮 刷新页面
    //if (_selectButton == button) {
    //    NSString *selectRefreshController = [NSString stringWithFormat:@"refreshView%ld",(long)button.tag];
    //    NSNotification * refresh = [NSNotification notificationWithName:selectRefreshController object:nil userInfo:@{@"tag":@"123"}];
    //    [[NSNotificationCenter defaultCenter] postNotification:refresh];
    //}
    _selectButton.selected = NO;
    button.selected = YES;
    _selectButton = button;
    
    // 修改下划线位置
    [UIView animateWithDuration:0.25 animations:^{
        _underLineView.centerX = button.centerX;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }];
    
}

#pragma mark - 点击标题
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    // 1.选中按钮
    [self selButton:button];
    
    // 2.设置collectionView偏离量
    CGFloat offsetX = i * ScreenW;
    _collectionView.contentOffset = CGPointMake(offsetX, 0);
}


#pragma mark - UICollectionViewDelegate
// 滚动完成的时候就会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 获取页码
    NSInteger page = scrollView.contentOffset.x / ScreenW;
    
    // 获取标题按钮
    UIButton *titleButton = self.buttons[page];
    
    // 选中标题
    [self selButton:titleButton];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.childViewControllers.count;
}

// 只要有新的cell出现就会调用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    // 移除其它子控制器view
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 添加对应的子控制器view 到 对应cell
    UIViewController *vc = self.childViewControllers[indexPath.row];
    // 添加到contentView
    [cell.contentView addSubview:vc.view];
    
    //    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    //
    return cell;
}


-(void)rightItemClicked{


}

@end
